package yuan.zk.watcher;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import yuan.zk.node.ZKCreate;

import java.util.concurrent.CountDownLatch;

/**
 * @version: 1.0
 * @Description: TODO
 * @author: zZmH
 * @date: 2020/09/11 16:46
 */


public class ZKConnectionWatcher implements Watcher {
    static CountDownLatch latch = new CountDownLatch(1);
    static ZooKeeper zooKeeper;

    @Override
    public void process(WatchedEvent event) {
        try {
            if (event.getType() == Event.EventType.None) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    System.out.println("connected successfully!");
                    latch.countDown();
                } else if (event.getState() == Event.KeeperState.Disconnected) {
                    System.out.println("shutdown the connection!");

                } else if (event.getState() == Event.KeeperState.Expired) {
                    System.out.println("session timeout!");
                    zooKeeper = new ZooKeeper(ZKCreate.ip, ZKCreate.TIME_OUT,
                            new ZKConnectionWatcher());
                } else if (event.getState() == Event.KeeperState.AuthFailed) {
                    System.out.println("authentication failure!");

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public static void main(String[] args) {
        try {

            zooKeeper = new ZooKeeper(ZKCreate.ip, ZKCreate.TIME_OUT,
                    new ZKConnectionWatcher());
            latch.await();
            System.out.println(zooKeeper.getSessionId());
            zooKeeper.addAuthInfo("digest",
                    "itcast:123456".getBytes());
            byte[] data = zooKeeper.getData("/node1",
                    false,
                    null);
            System.out.println(new String(data));
            zooKeeper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
